<?php

namespace app\manage\controller;

use think\Db;
use think\Log;
use app\common\controller\BaiduService;
use app\common\controller\TengxunService;
use app\common\controller\JuliangService;

/**
 * 账户城市准入
 */
class AccountCityIn extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }


    public function index()
    {
        $acc_name = input('acc_name','');
        $status = input('status','');
        $cityname = input('cityname','');

        $map = [];

        //模糊查询城市
        if(!empty($cityname)){
            $cityIdArr=Db::name('city')->field('id,type,pid')->where('name','like',$cityname."%")->where('type',2)->find();
            if($cityIdArr){
                $map['a.city']=$cityIdArr['pid'].'-'.$cityIdArr['id'];
            }else{
                $map['a.city']=0;
            }
        }

        if($acc_name!=''){
            $accId=model('Account')->where('like','%'.$acc_name.'%')->column('id');
            $map['acc_id']=['in',$accId];
        }

        if($status!=''){
            $map['status']=$status;
        }
        $accountAll=Db::name('Account')->column('acc_name','id');

//        $infos = model('Push')->getInfosByMap($map, '', false);
        $infos = model('AccountCityIn')->alias('a')
            ->where($map)
            ->order('id desc')->paginate(100);
        foreach ($infos as $k=>$v){
            $infos[$k]['acc_name']=$accountAll[$v['acc_id']];

            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $prov = $this->getCityName($ids[0]);
                $city = $this->getCityName($ids[1]);
                if($prov == $city){
                    $infos[$k]['city'] = $prov;
                }else{
                    $infos[$k]['city'] = $prov.'-'.$city;
                }
            }

        }

        $account = model('Account')->getListByMap();;


        return $this->fetch('',[
            'infos' => $infos,
            'acc_name' => $acc_name,
            'status' => $status,
            'province' => Db::name('city')->where(['pid'=>1])->select(),
            'group_id' => $this->group_id,
            'cityname' => $cityname,
            'account' => $account,
        ]);
    }

    public function citySave()
    {
        if (request()->isAjax()) {
            try {

                $id = input('post.id');
                $save_data = input('post.');

                if (empty($save_data['acc_id'])) {
                    return self::showReturnCode(1011, '请选择账户');
                }

                if (empty($save_data['content'])) {
                    return self::showReturnCode(1011, '请选择城市');
                }

                $content = explode("\n", $save_data['content']);
                $content = array_unique($content);

                $city = \db('city')->where('type', 2)->column('id, pid','name'); // 城市
                foreach ($content as $v) {
                    if (empty($v)) continue;
                    if (empty($city[$v])) {
                        return self::showReturnCode(1011, '市级城市解析有误：'.$v. "不在数据库中");
                    }
                }

                $time = time();
                if (!empty($id)) { // 编辑
                    \db('account_city_in')->where('pid', $id)->delete();
                    $update_group = [
                        'acc_id' => $save_data['acc_id'],
                        'city' => implode(',', $content),
                        'accept_limit_num' => $save_data['accept_limit_num'],
                        'update_time' => $time,
                    ];
                    \db('account_city_in_group')->where('id', $id)->update($update_group);
                    $pack_id = $id;
                } else { // 新增
                    $insert_group = [
                        'acc_id' => $save_data['acc_id'],
                        'city' => implode(',', $content),
                        'accept_limit_num' => $save_data['accept_limit_num'],
                        'create_time' => $time,
                        'update_time' => $time,
                    ];
                    $pack_id = \db('account_city_in_group')->insertGetId($insert_group);
                }

                $insert = [];
                foreach ($content as $v) {
                    if (empty($v)) continue;
                    $insert[] = [
                        'pid' => $pack_id,
                        'acc_id' => $save_data['acc_id'],
                        'city' => $city[$v]['pid'].'-'.$city[$v]['id'],
                        'status' => 1,
                        'accept_limit_num' => $save_data['accept_limit_num'],
                        'create_time' => $time,
                        'update_time' => $time,
                    ];
                }
                unset($content);
                \db('account_city_in')->insertAll($insert);

                $this->RecordSystemLog($this->uid, $this->behavior, '准入城市保存成功');

                return self::showReturnCode(1001, '保存成功');
            } catch (\Exception $e) {
                Log::error($e->getMessage());
                return self::showReturnCode(1011, $e->getMessage());
            }
        } else {
            return self::showReturnCode(1002);
        }
    }

    public function cityStatus()
    {
        if($this->request->isAjax()){
            $id = input('post.id');
            $res = model('AccountCityIn')->save(['status'=>input('post.status')],['id'=>$id]);
            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'状态操作成功,操作ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'操作失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }

    public function edit()
    {
        $id = input('id');
        if (!$id) return self::showReturnCode(1002, 'id 错误');

        $city_list = \db('account_city_in')->find($id);
        $info = \db('account_city_in_group')->where('id', $city_list['pid'])->find();

        $info['content'] = implode("\n", explode(",", $info['city']));

        return self::showJsonReturnCodeData('1001', $info, '');
    }

    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id');

            $res = \db('account_city_in')->where('id', $id)->find();
            $ref = \db('account_city_in')->where('pid', $res['pid'])->delete();
            \db('account_city_in_group')->where('id', $res['pid'])->delete();
            if ($ref) {
                $this->RecordSystemLog($this->uid, $this->behavior, '删除成功,操作ID: ' . $id);
                return $this->showReturnCode(1001, '删除成功');
            } else {
                return $this->showReturnCode(1009, '删除失败');
            }
        } else {
            return $this->showReturnCode(1002);
        }
    }

    /*编辑每日接收数量*/
    public function edit_accept_limit_num()
    {
        if($this->request->isAjax()){
            $id = input('id');
            $listorder = input('accept_limit_num');
            if(!is_numeric($id) || !is_numeric($listorder)){
                return $this->showReturnCode(1003);
            }
            //获取控制器
            $model = request()->controller();
            $res =  model($model)->save(['accept_limit_num'=>$listorder], ['id'=>$id]); //跟新排序
            if($res){
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'排序失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }
}